package main

import (
	"fmt"
	"iot-base/common/cache"
	ca "iot-base/common/cache/alarm"
	"iot-base/common/config"
	_ "iot-base/common/ctrl"
	"iot-base/common/dbobj"
	"iot-base/common/event"
	"iot-base/common/eventtype"
	"iot-base/common/idsync"
	"iot-base/common/logger"
	"iot-base/common/notify"
	"iot-base/common/property"
	"iot-base/common/types"
	_ "iot-base/dm/common/state"
	"iot-base/dm/edge/north"
	"sync"
)

//InitListenAlarm 初始化告警处理模块
func InitListenAlarm() {
	notify.SubRawAlarm(func(curAlarm *eventtype.Alarm) {
		//curAlarm, _ := alarm.(*eventtype.Alarm)
		if curAlarm.Flag == "BEGIN" {
			event.ThingAlarm(curAlarm)
		} else {
			event.ThingAlarmClear(curAlarm)
		}
	})
	notify.SubAllAlarmReport(func(ids []string, alarms []*eventtype.Alarm) {
		//fmt.Println("-------begin---------------")
		event.SyncAlarms(ids, alarms)
		//fmt.Println("---------------end------------")
	})
	notify.SubMsg(true, "objRemoved", nil, func(t string, b interface{}) {
		id, ok := b.(string)
		if ok {
			event.RemoveActiveAlarm(id)
			ca.RemoveAlarmByTID(id)
			cache.RemoveDevData(id)
			fmt.Println("-----------send alarm changed -----------------")
			notify.PubMsg(false, "alarmChanged", id)
		}
	})
	//上报记录.
	notify.SubMsg(true, "ReportData", &types.ReqRecordData{}, func(t string, b interface{}) {
		// 发送给云端端
		if data, ok := b.(*types.ReqRecordData); ok {
			north.SendRecord(*data)
		}
	})
}

//InitListenData 初始化数据处理模块
func InitListenData() {
	property.InitDataHandler()
	//默认设备控制，返回错误

}

func initNorthInterface() {
	go north.InitDataPicker()
}

func main() {
	logger.Log.Warn("---------DM in Edge---------running-----1.00000xxx-----" + config.SelfOption.ID)
	idsync.BeginSynIDThrd(&dbobj.Thing{})

	InitListenAlarm()
	logger.Log.Info("------------alarm ready----------------")
	InitListenData()
	logger.Log.Info("------------data ready----------------")
	initNorthInterface()
	logger.Log.Info("------------north interface----ready------------")

	logger.Log.Info("------------all ready----------------")
	wg := sync.WaitGroup{}
	wg.Add(1)
	wg.Wait()
}
